package com.skyz.base.manager;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;

import java.lang.ref.WeakReference;
import java.util.Iterator;
import java.util.Stack;

public class ActivityManager {
    private final String TAG = getClass().getSimpleName();

    private ActivityManager() {
    }

    private static class InstanceHolder {
        private static final ActivityManager instance = new ActivityManager();
    }

    public static ActivityManager getInstance() {
        return InstanceHolder.instance;
    }

    private final Stack<WeakReference<Activity>> mActivityStack = new Stack<>();

    private class ApplicationActivityLifecycleCallbacks implements Application.ActivityLifecycleCallbacks {
        @Override
        public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityCreated");
            addActivity(activity);
        }

        @Override
        public void onActivityStarted(@NonNull Activity activity) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityStarted");
        }

        @Override
        public void onActivityResumed(@NonNull Activity activity) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityResumed");
        }

        @Override
        public void onActivityPaused(@NonNull Activity activity) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityPaused");
        }

        @Override
        public void onActivityStopped(@NonNull Activity activity) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityStopped");
        }

        @Override
        public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivitySaveInstanceState");
        }

        @Override
        public void onActivityDestroyed(@NonNull Activity activity) {
            Log.i(TAG, activity.getClass().getName() + " ===> onActivityDestroyed");
            finishActivity(activity);
        }
    }

    public void init(Application application) {
        application.registerActivityLifecycleCallbacks(new ApplicationActivityLifecycleCallbacks());
    }

    /**
     * 添加Activity到栈
     *
     * @param activity
     */
    public void addActivity(Activity activity) {
        mActivityStack.add(new WeakReference<>(activity));
    }

    /**
     * 获取当前Activity(栈中最后一个压入的）
     *
     * @return
     */
    public Activity currentActivity() {
        checkWeakReference();
        if (!mActivityStack.isEmpty()) {
            return mActivityStack.lastElement().get();
        }
        return null;
    }

    /**
     * 检查弱引用是否释放，若释放，则从栈中清理掉该元素
     */
    private void checkWeakReference() {
        for (Iterator<WeakReference<Activity>> iterator = mActivityStack.iterator(); iterator.hasNext(); ) {
            WeakReference<Activity> activityWeakReference = iterator.next();
            Activity activity = activityWeakReference.get();
            if (activity == null) {
                iterator.remove();
            }
        }
    }

    /**
     * 关闭当前Activity(栈中最后一个压入的）
     */
    public void finishActivity() {
        Activity activity = currentActivity();
        if (activity != null) {
            finishActivity(activity);
        }
    }

    /**
     * 关闭指定的Activity
     *
     * @param activity
     */
    public void finishActivity(Activity activity) {
        if (activity != null) {
            for (Iterator<WeakReference<Activity>> iterator = mActivityStack.iterator(); iterator.hasNext(); ) {
                WeakReference<Activity> activityWeakReference = iterator.next();
                Activity temp = activityWeakReference.get();
                //清理掉已经释放的activity
                if (temp == null) {
                    iterator.remove();
                    continue;
                }
                if (temp == activity) {
                    iterator.remove();
                }
            }
            activity.finish();
        }
    }

    /**
     * 结束所有Activity
     */
    public void finishAllActivity() {
        for (WeakReference<Activity> activityWeakReference : mActivityStack) {
            Activity activity = activityWeakReference.get();
            if (activity != null) {
                activity.finish();
            }
        }
        mActivityStack.clear();
    }

    /**
     * 退出应用
     */
    public void exitApp(int status) {
        try {
            finishAllActivity();
            System.exit(status);
            android.os.Process.killProcess(android.os.Process.myPid());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
